package tax.szz.mini.core.factory;

import cn.hutool.core.lang.ClassScanner;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.*;
import tax.szz.mini.core.register.MapperFactoryBean;

import java.util.Set;

/**
 * 作者：沈自在 <a href="https://www.szz.tax">Blog</a>
 *
 * @description 辅助将 Mapper 注册到Spring中，后续会改为 Scanner 进行扫描
 * @date 2023/12/15
 */
public class MapperScannerRegister implements BeanDefinitionRegistryPostProcessor {

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        // 1. 扫描包
        Set<Class<?>> classes = ClassScanner.scanPackage("tax.szz.mini.test.mapper");
        for (Class<?> clazz : classes) {

            // 1. 创建 BeanDefinition
            RootBeanDefinition beanDefinition = new RootBeanDefinition(clazz);
            String beanClassName = clazz.getName();

            // 2. 设置 BeanName
            beanDefinition.setBeanClassName(beanClassName);
            beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(beanClassName);
            beanDefinition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
            beanDefinition.setBeanClass(MapperFactoryBean.class);

            registry.registerBeanDefinition(StrUtil.lowerFirst(clazz.getSimpleName()), beanDefinition);
        }
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

    }
}
